<template>
    <div class="docIndex">
      <div class="docIndex_head" style="display: flex;">
        <el-form :model="queryForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="所属目录">
            <div @click="openDrawer">
              <el-input v-model="form.treeIndexDesc" placeholder="单击此处选择发布目录" readonly />
            </div>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-input v-show="false" v-model="queryForm.treeIndex" />
          </el-form-item>
          <el-form-item label-width="20px">
            <el-checkbox v-model="checked" style="margin-right:15px;">包含下级</el-checkbox>
          </el-form-item>
          <el-form-item label="文件标题：">
            <el-input maxlength="50" v-model="queryForm.docTitle" size="small" placeholder="请输入文章标题"
              @keyup.enter.native="inquire" />
          </el-form-item>
          <el-form-item label="文件发文日期：">
            <el-date-picker v-model="fileReleaseUnitDate" type="daterange" range-separator="-" size="small"
              value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" @change="dataPickerChange" />
          </el-form-item>
          <el-form-item label="发布状态：">
            <el-select v-model="queryForm.fileIsPublic" placeholder="请选择" size="small">
              <el-option v-for="item in fStateList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label-width="20px" style="margin-left: 0px; margin-right: 0;flex-basis: 21%;">
            <el-button size="small" @click="reset">
              重 置
            </el-button>
            <el-button type="primary" size="small" @click="getFileDataList">
              查 询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="docIndex_table">
        <div class="docIndex_table_top">
          <div>共 {{ totalPage }} 篇文章</div>
          <div>
            <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="postArticle">
              发布文件
            </el-button>
            <el-button type="primary" size="small" @click="fileBaseUpdateSort">
              调整排序
            </el-button>
          </div>
        </div>
        <el-main class="main_table" ref="container">
          <vxe-table :data="fileTableData" :header-cell-style="{
            color: '#606266',
            fontSize: '15px',
            fontWeight: '700',
          }" style="width: 100%; margin-bottom: 20px" expandRowKeys="id" :indent="indentNumber" highlight-current-row
            border
            :resizable=true
            >
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="fileTitle" title="文档标题">
              <template slot-scope="scope">
                <div>
                  <img class="docIcon" :src="require(`@/views/office/zzbPskh/assets/images/pdf.png`)
                    ">
                  <span class="docText">{{ scope.row.fileTitle ? scope.row.fileTitle : "-" }}</span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="fileReleaseUnitName" title="发文单位" width="200" />
            <vxe-column field="fileSecrecyLevel" title="保密级别" width="120" />
            <vxe-column field="fileIsPublic" title="发布状态" width="120">
              <template slot-scope="scope">
                <el-tag type="danger" v-if="scope.row.fileIsPublic == 0">
                  未发布
                </el-tag>
                <el-tag type="success" v-if="scope.row.fileIsPublic == 1">
                  已发布
                </el-tag>
              </template>
            </vxe-column>
            <vxe-column field="fileReleaseUnitDate" title="发文时间" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.fileReleaseUnitDate != null"
                  v-text="scope.row.fileReleaseUnitDate.substring(0, 10)" />
              </template>
            </vxe-column>
            <vxe-column field="fileLookCount" title="浏览记录" width="120" />
            <vxe-column field="fileDownloadCount" title="下载次数" width="120" />
            <vxe-column title="操作" align="center" header-align="center" width="250">
              <template slot-scope="scope">
                <div class="table_operate">
                  <el-button type="primary" plain size="small" @click="tableEdit(scope.row, 'look')">
                    查看
                  </el-button>
  
                  <el-button type="primary" plain size="small" @click="tableEdit(scope.row, 'edit')">
                    编辑
                  </el-button>
  
                  <el-button type="danger" plain size="small" style="color: red" @click="tableDel(scope.row.fileId)">
                    删除
                  </el-button>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </el-main>
        <div class="bot_pagination">
          <vxe-pager background @page-change="handleCurrentChange" :current-page.sync="page.currentPage"
            :page-size.sync="page.pageSize" :layouts="[
              'PrevJump',
              'PrevPage',
              'JumpNumber',
              'NextPage',
              'NextJump',
              'Sizes',
              'FullJump',
              'Total',
            ]" :total="totalPage" />
        </div>
      </div>
      <el-drawer title="请点击选择上传目录" :visible.sync="drawer" :direction="direction" ref="tclb" width="20%"
        :before-close="handleCloseDrawer" :append-to-body="true">
        <div class="tree mt10">
          <el-tree :data="treedata" :props="props" :load="loadNode" lazy v-model="checkedNodes"
            @node-click="handleNodeClick" />
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="drawer = false">确定</el-button>
        </div>
      </el-drawer>
      <uploadNewFile ref="uploadNewFileRef" v-if="showaddonevvFlag" @refresh="getFileDataList" />
      <fileBaseUpdateSort ref="fileBaseUpdateSortRef" v-if="fileBaseUpdateSortFlag" :sub-tree-data="subTreeData"
        @refresh="getFileDataList"></fileBaseUpdateSort>
    </div>
  </template>
  <script>
  import uploadNewFile from "./uploadNewFile";
  import {
    fileBaseList,
    fileBaseDelete,
  } from "@/api/knowledge/fileBase";
  import store from "@/store";
  import { getTreeDataList } from "@/api/knowledge/diretory";
  import fileBaseUpdateSort from "./fileBaseUpdateSort";
  
  export default {
    name: `NewDocIndex`,
    components: { uploadNewFile, fileBaseUpdateSort },
    data() {
      return {
        showaddonevvFlag: false,
        fileBaseUpdateSortFlag: false,
        subTreeData: [],
        checked: false,
        indentNumber: 24,
        userDeptId: null,
        // 表格数据
        heightY: `${window.innerHeight - 150}px`,
        cascadrValue: [],
        selectTreeItems: ``,
        // 请求参数
        queryForm: {
          // 文件名称
          docTitle: null,
          fileIsPublic: null,
          range: 1,
          // 发布开始日期
          releaseTimeStart: null,
          // 发布结束日期
          releaseTimeEnd: null,
          // 文件类型
          fileType: null,
          // 所属系统
          fileSystem: null,
          treeIndex: `0001`,
        },
        page: {
          currentPage: 1,
          pageSize: 20,
        },
        // 发布日期
        fileReleaseUnitDate: ``,
        // 文件总数
        totalPage: 0,
        // 应用系统列表
        sysList: [],
        // 文件类型列表
        fileTypeList: [],
        // 发布文件类型的下拉框
        ftypeList: [
          {
            name: `文件类型`,
            value: 0,
          },
          {
            name: `链接类型`,
            value: 1,
          },
        ],
        // 文章状态的下拉框
        fStateList: [
          {
            name: `未发布`,
            value: 0,
          },
          {
            name: `已发布`,
            value: 1,
          },
        ],
        rangeList: [
          {
            name: `本部门`,
            value: 1,
          },
          {
            name: `全部`,
            value: 0,
          },
        ],
        // nodeId: "0001",
  
        // 文件数据列表
        fileTableData: [],
        tableHeight: 0,
        screenHeight: 0,
        setupVisible: false,
        checkAll: false,
        isIndeterminate: false,
        showTable: true,
        loadingShowTable: false,
        loadingTable: false,
        cascadrValue: [],
        cascaderIdx: 0,
        shouldCollapse: false,
        fileBussinessTypeCode: "111",
        drawer: false,
        direction: "ltr",
        form: {
          treeIndexDesc: "",
        },
        checkedNodes: [],
        treedata: [], //tree数据
        props: {
          label: `name`,
          children: `children`, // 显示子节点的字段名
          isLeaf: (node) => !node.isParent && !node.children,
        },
      };
    },
    mounted() {
      const that = this;
      this.$nextTick(() => {
        this.tableHeight = this.$refs.container.$el.clientHeight;
      });
      window.onresize = function () {
        that.screenHeight = document.documentElement.clientHeight;
      };
    },
    watch: {
      screenHeight(val) {
        this.tableHeight = this.$refs.container.$el.clientHeight;
      },
      cascadrValue() {
        if (this.$refs.cascader) {
          this.$refs.cascader.dropDownVisible = false
        }
      },
    },
    created() {
      this.init();
      this.getFileDataList();
      this.getTreeData();
    },
    methods: {
      init() {
        this.showaddonevvFlag = true;
        this.fileBaseUpdateSortFlag = true;
      },
      getFileDataList() {
        let isContainsOrgChild = '1'
        if (this.checked == false) {
          isContainsOrgChild = '0'
        }
        const params = {
          data: {
            fileDiretoryId: this.queryForm.treeIndex,
            pageSize: this.page.pageSize,
            currentPage: this.page.currentPage,
            fileTitle: this.queryForm.docTitle, //文档标题
            fileIsPublic: this.queryForm.fileIsPublic, //是否发布
            fileReleaseUnitDateStart: this.queryForm.releaseTimeStart,
            fileReleaseUnitDateEnd: this.queryForm.releaseTimeEnd,
            isContensDown: isContainsOrgChild,
          },
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
        };
        fileBaseList(params).then((data) => {
          if (data.result) {
            this.fileTableData = data.resultdata.data;
            this.totalPage = data.resultdata.count;
            this.loadingShowTable = false;
            // 将查询结果赋值给subTreeData
            this.subTreeData = this.fileTableData;
          }
        });
      },
      openDrawer() {
        this.drawer = true;
        this.getTreeData();
      },
      handleCloseDrawer() {
        this.drawer = false;
      },
      getTreeData() {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          data: {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryId: null,
          },
        };
        getTreeDataList(params).then((data) => {
          if (data.result === true) {
            this.treedata = data.resultdata.data;
          }
          else {
            this.$message({
              type: `warning`,
              message: `获取信息出错`,
            });
          }
        });
      },
      loadNode(node, resolve) {
        if (node.level === 0) {
          return resolve(this.treedata);
        }
        if (node.level > 9999) return resolve([]);
        // 请求子节点数据
        setTimeout(() => {
          const params = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryId: node.data.id,
            },
          };
          getTreeDataList(params).then((data) => {
            if (data.result === true) {
              node.childNodes = [...node.childNodes, ...data.resultdata.data];
              const updatedChildren = node.childNodes.map((child) => {
                child.checked =
                  this.checkable &&
                  this.checkedNodes.some((node) => node.id === child.id);
                return child;
              });
              resolve(updatedChildren);
            }
            else {
              this.$message({
                type: `warning`,
                message: `获取信息出错`,
              });
            }
          });
        }, 500);
      },
      //点击tree树进行选择
      handleNodeClick(data, b, c) {
        this.queryForm.treeIndex = data.id;
        this.form.treeIndexDesc = data.name;
        this.$refs.tclb.closeDrawer();
      },
      //调整排序
      fileBaseUpdateSort() {
        this.fileBaseUpdateSortFlag = true;
        this.$nextTick(() => {
          this.$refs.fileBaseUpdateSortRef.init();
        })
        // 触发查询并刷新subTreeData
        this.getFileDataList();
      },
  
      handleCurrentChange({ currentPage, pageSize }) {
        //选择跳转多少页
        this.page.currentPage = currentPage;
        this.page.pageSize = pageSize;
        console.log(this.page.currentPage, this.page.pageSize, "1")
        this.getFileDataList();
      },
      // 日期选择
      dataPickerChange() {
        this.queryForm.releaseTimeStart = this.fileReleaseUnitDate && this.fileReleaseUnitDate[0] ? this.fileReleaseUnitDate[0] : null;
        this.queryForm.releaseTimeEnd = this.fileReleaseUnitDate && this.fileReleaseUnitDate[1] ? this.fileReleaseUnitDate[1] : null;
      },
      reset() {
        //重置
        this.queryForm.docTitle = null;
        this.fileReleaseUnitDate = null;
        this.queryForm.releaseTimeStart = null;
        this.queryForm.releaseTimeEnd = null;
        this.queryForm.fileType = null;
        this.queryForm.fileSystem = null;
        this.queryForm.fileIsPublic = null;
        this.queryForm.range = 0;
        this.selectTreeItems = [];
        this.queryForm.treeIndex = ``;
        this.cascadrValue = [];
        this.queryForm.treeIndex = `0001`;
        this.checked = "";
        this.form.treeIndexDesc = "";
      },
      inquire() { },
      // 发布和取消发布
      async fabuAndCancelHandle(row) { },
      //打开修改页面
      tableEdit(row, flag) {
        this.showaddonevvFlag = true;
        this.$nextTick(() => {
          this.$refs.uploadNewFileRef.init(row.fileId, flag);
        });
      },
  
      tableDel(id) {
        this.$confirm(`是否删除此条记录?`, `提示`, {
          confirmButtonText: `确定`,
          cancelButtonText: `取消`,
          type: `warning`,
        }).then(() => {
          const params = {
            data: { fileId: id },
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
          };
          fileBaseDelete(params).then((data) => {
            if (data.result) {
              this.$message({
                type: `success`,
                message: `删除成功`,
              });
              this.getFileDataList();
              // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
              const total = Math.ceil((this.totalPage - 1) / this.page.pageSize); // 总页数
              this.page.currentPage =
                this.page.currentPage > total ? total : this.page.currentPage;
  
              this.page.currentPage =
                this.page.currentPage < 1 ? 1 : this.page.currentPage;
            }
          });
        });
      },
  
      postArticle() {
        this.showaddonevvFlag = true;
        this.$nextTick(() => {
          this.$refs.uploadNewFileRef.init();
        });
      },
    },
  };
  </script>
  
  <style scoped lang="scss">
  * {
    scrollbar-width: thin;
    scrollbar-color: #333 transparentize;
  }
  
  .docIcon {
    vertical-align: middle;
    width: 48px;
    height: 48px;
  }
  
  .docText {
    vertical-align: middle;
  }
  
  >>>.el-form {
    margin-top: 15px !important;
  }
  
  .external-frame .external-frame-content .router-view {
    padding: 10px !important;
    background: #eee !important;
  }
  
  .docIndex {
    height: calc(100% - 125px);
    background: #eee;
  
    &_head {
      height: 112px;
      background: #ffffff;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24px;
      box-sizing: border-box !important;
      flex-wrap: wrap;
  
      .form_item {
        flex: 1;
        margin-right: 10px;
  
        &_title {
          font-size: 14px;
          color: #000000;
          line-height: 24px;
          margin-bottom: 8px;
        }
  
        &_number {
          display: flex;
          width: 220px;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          color: #000000;
          line-height: 22px;
  
          >.el-input-number {
            width: 100px;
  
            .el-input--small {
              .el-input__inner {
                padding: unset;
                padding-left: 10px;
              }
            }
          }
        }
  
        .el-date-editor {
          width: 260px;
        }
      }
  
      .form_button {
        margin-right: 8px;
  
        &_title {
          height: 24px;
          margin-bottom: 8px;
        }
      }
    }
  
    &_table {
      width: 100%;
      background: #ffffff;
      border-radius: 4px;
      height: calc(100vh - 124px - 50px);
      margin-top: 10px;
      box-sizing: border-box;
      padding: 0 24px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 24px;
  
      &_top {
        height: 64px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
  
      .table_operate {
        display: flex;
        justify-content: space-around;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #579ef8;
        line-height: 22px;
        //width: 125px;
  
        .edit {
          cursor: pointer;
        }
  
        .del {
          color: #f85757;
          cursor: pointer;
        }
      }
  
      .bot_pagination {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: 60px;
        margin-top: 30px;
      }
    }
  }
  
  .main_table {
    height: calc(100vh - 124px - 112px - 24px - 64px - 60px);
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    scrollbar-width: thin;
    scrollbar-color: #333 transparentize;
  
    .el-table {
      >.el-table__body-wrapper {
        scrollbar-width: thin;
        scrollbar-color: #333 transparentize;
      }
    }
  }
  
  .el-form {
    display: flex !important;
    margin-top: 20px;
  }
  
  .docIndex_head {
    height: 60px;
  }
  </style>
  <style lang="scss">
  .search_cascader .el-checkbox__inner {
    border: 2px solid #999 !important;
  }
  
  .el-tree {
    min-width: 100%;
    height: calc(100% - 150px);
    display: inline-block;
  }
  
  .tree {
    overflow: auto;
    height: 800px;
    min-width: 100%;
  }
  
  .demo-drawer__footer .el-button {
    width: 270px;
    height: 35px;
    margin-left: 5px;
    margin-bottom: 10px;
  }
  </style>
  